"""
订单相关视图
"""
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.db.models import F
from django.db import transaction
from pecco_site.models import Order, ProductVariant
from ..serializers.order import (
    OrderSerializer,
    OrderListSerializer,
    CreateOrderSerializer
)
import logging

logger = logging.getLogger(__name__)


class OrderViewSet(viewsets.ReadOnlyModelViewSet):
    """订单视图集"""
    permission_classes = [IsAuthenticated]
    
    def get_serializer_class(self):
        if self.action == 'list':
            return OrderListSerializer
        elif self.action == 'create_order':
            return CreateOrderSerializer
        return OrderSerializer
    
    def get_queryset(self):
        """只返回当前用户的订单"""
        return Order.objects.filter(user=self.request.user).prefetch_related(
            'items', 'status_history'
        )
    
    @action(detail=False, methods=['post'])
    def create_order(self, request):
        """创建订单"""
        serializer = CreateOrderSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            order = serializer.save()
            order_serializer = OrderSerializer(order, context={'request': request})
            return Response(order_serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=True, methods=['post'])
    def cancel(self, request, pk=None):
        """取消订单"""
        order = self.get_object()

        if order.status not in ['processing']:
            return Response(
                {'error': 'Order cannot be cancelled at this stage.'},
                status=status.HTTP_400_BAD_REQUEST
            )

        with transaction.atomic():
            # 更新订单状态
            order.status = 'cancelled'
            order.save()

            # 记录状态变更
            from pecco_site.models import OrderStatusHistory
            OrderStatusHistory.objects.create(
                order=order,
                status='cancelled',
                note='Cancelled by customer'
            )

            # 使用 F 表达式原子回滚库存
            logger.info(f"用户取消订单 {order.order_number}，开始回滚库存")

            for item in order.items.all():
                if item.variant:
                    # 使用 F 表达式原子增加库存（防止并发问题）
                    updated_count = ProductVariant.objects.filter(
                        id=item.variant.id
                    ).update(stock=F('stock') + item.quantity)

                    if updated_count > 0:
                        logger.info(
                            f"库存回滚成功: 订单 {order.order_number}, "
                            f"商品 {item.product_name} (variant_id={item.variant.id}), "
                            f"回滚数量 {item.quantity}"
                        )
                    else:
                        logger.error(
                            f"库存回滚失败: 订单 {order.order_number}, "
                            f"商品 {item.product_name} (variant_id={item.variant.id}), "
                            f"变体可能已被删除"
                        )

        return Response(OrderSerializer(order).data)

